﻿using System;
using System.Web.UI;
using mojoPortal.Web.Framework;
using mojoPortal.Web;
using ud_Video.Business;
using System.Configuration;
using ud_Utilities;
using Resources;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.IO;
using Brettle.Web.NeatUpload;
using System.Collections;
using mojoPortal.Business;

namespace ud_Video.UI
{

    public partial class VideoEditPage : mojoBasePage
    {
        private int moduleId = -1;
        private int pageId = -1;
        private ud_VideoClip item;
        private Guid itemGuid = Guid.Empty;
        readonly DBVideoClip repository = new DBVideoClip();
        protected string DeleteLinkText = VideoResource.ButtonDelete;
        protected string EditLinkText = VideoResource.ButtonEdit;
        private VideoConfiguration config = new VideoConfiguration();
        #region OnInit

        protected override void OnPreInit(EventArgs e)
        {
            AllowSkinOverride = true;
            base.OnPreInit(e);
        }

        override protected void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Load += Page_Load;
            btnSave.Click += btnSave_Click;
            gvItems.RowCommand += gvItems_RowCommand;
            gvItems.RowDataBound += gvItems_RowDataBound;
            gvItems.PageIndexChanging += gvItems_PageIndexChanging;
            btnNew.Click += btnNew_Click;
            btnDelete.Click += btnDelete_Click;
            btnDeleteImg.Click += btnDeleteImg_Click;
            LoadSideContent(true, true, true, true, 0);
        }

        void btnDeleteImg_Click(object sender, ImageClickEventArgs e)
        {
            if (item == null) { item = repository.GetOne(itemGuid); }
            DeleteImageFromServer();
            divImage.Visible = false;
            item.ImageURL = string.Empty;
            repository.Update(item.Guid, item.Name, item.VideoURL, item.ImageURL, item.Description, item.IsPublished);
        }

        void btnDelete_Click(object sender, EventArgs e)
        {
            if (item == null)
            {
                item = repository.GetOne(itemGuid);
            }
            DeleteVideoFromServer(item.VideoURL);
            repository.Delete(itemGuid);
            Refresh(string.Empty);
        }

        void btnNew_Click(object sender, EventArgs e)
        {
            Refresh(string.Empty);
        }


        #endregion

        private void Page_Load(object sender, EventArgs e)
        {
            Page.EnableViewState = true;
            LoadSettings();

            PopulateLabels();
            PopulateControls();
        }

        private void PopulateControls()
        {
            BindData();
            if (!Page.IsPostBack)
            {
                BindEdit();
            }
            SetUpJQuery();
        }

        private void BindEdit()
        {
            if (itemGuid == Guid.Empty) return;
            item = repository.GetOne(itemGuid);
            txtName.Text = item.Name;
            txtDescription.Text = item.Description ?? string.Empty;
            chkPublish.Checked = item.IsPublished;
            divVideo.Visible = true;
            string link = ImageSiteRoot + "/" + ConfigurationManager.AppSettings["VideoFolder"] + item.VideoURL;
            hplItem.NavigateUrl = link;
            hplItem.Attributes.Add("class", "media {width:250, height:250}");
            if (!string.IsNullOrEmpty(item.ImageURL))
            {
                divImage.Visible = true;
                imgView.ImageUrl = "~/" + ConfigurationManager.AppSettings["VideoFolder"] + item.ImageURL;
            }
            else { divImage.Visible = false; }
        }

        private void SetUpJQuery()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<script src='" + ImageSiteRoot + "/ClientScript/media/jquery.metadata.js' type='text/javascript'></script>");
            sb.Append("<script src='" + ImageSiteRoot + "/ClientScript/media/jquery.media.js' type='text/javascript'></script>");
            sb.Append("<script type='text/javascript'>");
            sb.Append("$(document).ready(function(){");
            sb.Append("$('a.media').media();");
            sb.Append("});");
            sb.Append("</script>");

            if (!Page.ClientScript.IsStartupScriptRegistered("video" + moduleId.ToInvariantString()))
            {
                Page.ClientScript.RegisterStartupScript(typeof(mojoUserControl), "video" + moduleId.ToInvariantString(), sb.ToString());
            }
        }

        void btnSave_Click(object sender, EventArgs e)
        {
            string fileName;
            string imageThumbnail;
            string error = string.Empty;
            if (itemGuid == Guid.Empty)
            {
                if (!nifVideo.HasFile)
                {
                    lblVideoUrlError.Text = VideoResource.NoFileWarning;
                    return;
                }
                if (SaveVideoUrl(ref error, out fileName) && SaveImageUrl(out imageThumbnail))
                {
                    repository.Create(moduleId, txtName.Text, fileName, imageThumbnail, txtDescription.Text, chkPublish.Checked);
                    Refresh(string.Empty);
                }
                else
                {
                    lblVideoUrlError.Visible = true;
                    lblVideoUrlError.Text = error;
                }
            }
            else
            {
                item = repository.GetOne(itemGuid);
                SaveVideoUrl(ref error, out fileName);
                SaveImageUrl(out imageThumbnail);
                fileName = fileName == string.Empty ? item.VideoURL : fileName;
                imageThumbnail = imageThumbnail == string.Empty ? item.ImageURL : imageThumbnail;
                repository.Update(itemGuid, txtName.Text, fileName, imageThumbnail, txtDescription.Text, chkPublish.Checked);
                itemGuid = Guid.Empty;
                Refresh(string.Empty);
            }
        }
        
        private void Refresh(string itemID)
        {
            if (itemID == string.Empty)
            {
                WebUtils.SetupRedirect(this, SiteRoot + "/VideoClip/Admin/VideoEdit.aspx?pageid=" + pageId.ToInvariantString() + "&mid=" + moduleId.ToInvariantString());
            }
            else
            {
                WebUtils.SetupRedirect(this, SiteRoot + "/VideoClip/Admin/VideoEdit.aspx?pageid="
                    + pageId.ToInvariantString() + "&mid=" + moduleId.ToInvariantString() + "&itemid=" + itemID);
            }
            
        }

        private void LoadSettings()
        {
            pageId = WebUtils.ParseInt32FromQueryString("pageid", moduleId);
            moduleId = WebUtils.ParseInt32FromQueryString("mid", true, moduleId);
            itemGuid = WebUtils.ParseGuidFromQueryString("itemid", itemGuid);
            pnlContainer.ModuleId = moduleId;
            Hashtable settings = ModuleSettings.GetModuleSettings(moduleId);
            config = new VideoConfiguration(settings);
            //if (ScriptController != null)
            //{
            //    ScriptController.RegisterAsyncPostBackControl(gvItems);
            //}
        }

        private void BindData()
        {
            List<ud_VideoClip> listVideoClip = repository.GetAll(moduleId);
            gvItems.DataSource = listVideoClip;
            gvItems.DataBind();
            gvItems.AllowPaging = listVideoClip.Count > gvItems.PageSize;
        }

        private void PopulateLabels()
        {
            Title = SiteUtils.FormatPageTitle(siteSettings, VideoResource.VideoEditPage);
            ltrTitle.Text = VideoResource.VideoEditPage;
            chkPublish.Text = VideoResource.CheckBoxPublished;
            btnSave.Text = VideoResource.ButtonSave;
            btnNew.Text = VideoResource.ButtonNew;
            btnDelete.Text = VideoResource.ButtonDelete;
            lblVideoUrlError.Text = VideoResource.ImageUrlErrorLabel + ConfigurationManager.AppSettings["AllowedVideoFileExtensions"]
                + @" -- " + VideoResource.ImageUrlErrorLabelFileSize + ConfigurationManager.AppSettings["AllowedVideoSize"] + @" KB";

            lblImageUrlError.Text = VideoResource.ImageUrlErrorLabel + ConfigurationManager.AppSettings["AllowedImageFileExtensions"]
                + @" -- " + VideoResource.ImageUrlErrorLabelFileSize + ConfigurationManager.AppSettings["AllowedImageSize"] + @" KB";

            gvItems.Columns[0].HeaderText = VideoResource.LabelName;
            gvItems.Columns[1].HeaderText = VideoResource.LabelDescription;
            UIHelper.DisableButtonAfterClick(
                btnSave,
                VideoResource.ButtonPleaseWait,
                Page.ClientScript.GetPostBackEventReference(btnSave, string.Empty)
                );
            if (itemGuid != Guid.Empty)
            {
                btnDelete.Visible = true;
                Utilities.AddConfirmButton(btnDelete, VideoResource.DeleteConfirmWarning);
            }
            lblVideoUrlError.ForeColor = Color.Blue;
            lblImageUrlError.ForeColor = Color.Blue;

            btnDeleteImg.ImageUrl = "~/Data/SiteImages/delete.gif";
            btnDeleteImg.ToolTip = VideoResource.ButtonDelete;

            npbVideo.AddTrigger(btnSave);
        }

        private bool SaveVideoUrl(ref string error, out string fileName)
        {
            bool flag = false;
            fileName = string.Empty;
            try
            {
                //Check valid file upload
                if (nifVideo.FileName.Trim().Length > 0)
                {
                    string fileExtension = Path.GetExtension(nifVideo.FileName);
                    Double fileSize = nifVideo.ContentLength / 1024;

                    //Kiem tra ten mo rong file upload
                    if (!Utilities.IsValidFileExtension(fileExtension, "AllowedVideoFileExtensions"))
                    {
                        error = VideoResource.ImageUrlErrorFileExtension;
                        return false;
                    }
                    //Kiem tra kich thuoc file upload
                    if (!Utilities.IsValidFileSize(fileSize, "AllowedVideoSize"))
                    {
                        error = VideoResource.ImageUrlErrorFileSize + ConfigurationManager.AppSettings["AllowedVideoSize"] + " KB";
                        return false;
                    }
                    string path = Server.MapPath("~/" + ConfigurationManager.AppSettings["VideoFolder"]);
                    string guid = Guid.NewGuid().ToString().Replace("-", "").ToUpper();
                    fileName = path + guid + fileExtension;
                    nifVideo.MoveTo(fileName, MoveToOptions.Overwrite);
                    fileName = guid + fileExtension;
                    if (item.VideoURL != null)
                    {
                        DeleteVideoFromServer(item.VideoURL);
                    }
                    flag = true;
                }
                else
                {
                    flag = true;
                }
            }
            catch (Exception e)
            {
                error = e.Message;
            }
            return flag;
        }

        private bool SaveImageUrl(out string fileName)
        {
            bool flag = false;
            int width = 0;
            int height = 0;
            fileName = string.Empty;
            try
            {
                //Check valid file upload
                if (nuImageUrl.HasFile && nuImageUrl.ContentLength > 0)
                {

                    string fileExtension = Path.GetExtension(nuImageUrl.FileName);
                    Double fileSize = nuImageUrl.ContentLength / 1024;

                    //Kiem tra ten mo rong file upload
                    if (!Utilities.IsValidFileExtension(fileExtension, "AllowedImageFileExtensions"))
                    {
                        lblImageUrlError.Text = VideoResource.ImageUrlErrorFileExtension;
                        return false;
                    }
                    //Kiem tra kich thuoc file upload
                    if (!Utilities.IsValidFileSize(fileSize, "AllowedImageSize"))
                    {
                        lblImageUrlError.Text = VideoResource.ImageUrlErrorFileSize + ConfigurationManager.AppSettings["AllowedImageSize"] + @" KB";
                        return false;
                    }
                    string path = Server.MapPath("~/" + ConfigurationManager.AppSettings["VideoFolder"]);
                    string guid = Guid.NewGuid().ToString().Replace("-", "").ToUpper();
                    System.Drawing.Image image = System.Drawing.Image.FromStream(nuImageUrl.FileContent);
                    nuImageUrl.FileContent.Close();
                    int thumbnailWidth = config.Width > 0 ? config.Width : 250;
                    int thumbnailHeight = config.Height > 0 ? config.Height : 200;
                    Utilities.ResizeImage(ref width, ref height, thumbnailWidth, thumbnailHeight, image.Width, image.Height);
                    fileName = path + guid + fileExtension;
                    if (height != 0)
                    {
                        using (Bitmap bitmap = new Bitmap(image, width, height))
                        {
                            bitmap.Save(fileName, image.RawFormat);
                        }
                    }
                    else
                    {
                        using (Bitmap bitmap = new Bitmap(image, image.Width, image.Width))
                        {
                            bitmap.Save(fileName, image.RawFormat);
                        }
                    }
                    fileName = guid + fileExtension;
                    if (!string.IsNullOrEmpty(item.ImageURL))
                    {
                        DeleteImageFromServer();
                    }
                    flag = true;
                }
                else
                {
                    flag = true;
                }
            }
            catch (Exception e)
            {
                lblImageUrlError.Visible = true;
                lblImageUrlError.Text = e.Message;//"Error when upload image";
            }
            return flag;
        }

        private void DeleteImageFromServer()
        {
            string thumbnailImageURL = Request.PhysicalApplicationPath + ConfigurationManager.AppSettings["VideoFolder"] + item.ImageURL;
            thumbnailImageURL = thumbnailImageURL.Replace("/", "\\");
            if (File.Exists(thumbnailImageURL))
            {
                File.Delete(thumbnailImageURL);
            }
        }

        private void DeleteVideoFromServer(string videoURL)
        {
            string URL = Request.PhysicalApplicationPath + ConfigurationManager.AppSettings["VideoFolder"] + videoURL;
            if (File.Exists(URL))
            {
                File.Delete(URL);
            }
        }


        void gvItems_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("EditItem"))
            {
                itemGuid = new Guid(e.CommandArgument.ToString());
                Refresh(itemGuid.ToString());
            }
            else if (e.CommandName.Equals("DeleteItem"))
            {
                itemGuid = new Guid(e.CommandArgument.ToString());
                if (item.VideoURL == null) { item = repository.GetOne(itemGuid); }
                DeleteVideoFromServer(item.VideoURL);
                repository.Delete(itemGuid);
                WebUtils.SetupRedirect(this, Request.RawUrl);
            }
        }

        void gvItems_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvItems.PageIndex = e.NewPageIndex;
            BindData();
        }

        void gvItems_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ImageButton ibtnDelete = e.Row.FindControl("ibtnDelete") as ImageButton;
                Utilities.AddConfirmButton(ibtnDelete, VideoResource.DeleteConfirmWarning);
            }
        }

        protected override void OnError(EventArgs e)
        {
            Exception lastError = Server.GetLastError();
            if ((lastError != null) && (lastError is NullReferenceException) && Page.IsPostBack)
            {
                if (lastError.StackTrace.Contains("Recaptcha"))
                {
                    Server.ClearError();
                    WebUtils.SetupRedirect(this, Request.RawUrl);
                }
            }
        }
    }
}
